package com.athl.netty.nio.chat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * @author hl
 * @Data 2020/8/30
 */
public class NioServer {

    private Selector selector;
    private ServerSocketChannel serverSocketChannel;
    private final Integer port = 6666;

    public NioServer() {
        try {
            serverSocketChannel = ServerSocketChannel.open();
            selector = Selector.open();
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            serverSocketChannel.socket().bind(new InetSocketAddress(port));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void listen() {
        while (true) {
            try {
                int count = selector.select(2000);
                if (count > 0) {
                    // 处理
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = selectionKeys.iterator();
                    if (iterator.hasNext()) {
                        SelectionKey selectionKey = iterator.next();
                        if (selectionKey.isAcceptable()) {
                            // 连接事件
                            SocketChannel socketChannel = serverSocketChannel.accept();
                            socketChannel.configureBlocking(false);
                            socketChannel.register(selector, SelectionKey.OP_READ);
                            System.out.println(socketChannel.getLocalAddress() + " 上线了 ");
                        }
                        if (selectionKey.isReadable()) {
                            // 读事件
                            readData(selectionKey);
                        }
                        iterator.remove();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 读事件  buffer --> socketChannel
     *
     * @param key
     */
    private void readData(SelectionKey key) {
        SocketChannel sc = null;
        try {
            sc = (SocketChannel) key.channel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int count = sc.read(buffer);
            if (count > 0) {
                // 读取到数据了
                String msg = new String(buffer.array());
                System.out.println("msg = " + msg);
                // 向其他客户端转发 (排除自己)
                sendInfo2OtherClient(msg, sc);
            }
        } catch (IOException e) {
            try {
                System.out.println(sc.getRemoteAddress() + "离线了。。。");
                // 取消注册
                key.cancel();
                // 关闭通道
                sc.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    /**
     * 向其他客户端转发  socketChannel --> buffer
     */
    private void sendInfo2OtherClient(String msg, SocketChannel self) throws IOException {
        System.out.println("服务器转发消息中 ... ");
        for (SelectionKey key : selector.keys()) {
            // 通过key 取出 socketChannel
            SocketChannel targetChannel = (SocketChannel) key.channel();
            // 排除自己
            if (targetChannel != self) {
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                // buffer(msg) --> socketChannel
                targetChannel.write(buffer);
            }
        }
    }

    public static void main(String[] args) {
        NioServer nioServer = new NioServer();
        nioServer.listen();
    }
}
